package cn.doitedu.api;


import beans.OrderBean;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.*;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/2/27
 * @Desc: 学大数据，上多易教育
 * 有如下订单数据:
 * 订单id,商品id,品类id,金额,订单创建时间
 * o1,p1,category_01,1800,1709027697000
 * o1,p2,category_01,1600,1709027697000
 * o1,p3,category_02,1600,1709027697000
 * o2,p3,category_02,1600,1709027697000
 * o3,p4,category_03,1200,1709027697000
 * <p>
 * 统计:
 * 1. 最近 5分钟的成交总额，要求每 1分钟输出一次结果；
 * 2. 每 5分钟，各品类各商品的下单数;
 * 3. 每 5分钟，成交金额最高的前3种商品及其成交金额
 **/
public class _28_Exercise_Window_3 {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.enableCheckpointing(5000);
        env.getCheckpointConfig().setCheckpointStorage("file:///d:/ckpt");

        DataStreamSource<String> stream = env.socketTextStream("localhost", 8899);

        DataStream<OrderBean> mapped = stream.map(s -> {
            String[] split = s.split(",");
            return new OrderBean(split[0], split[1], split[2], Double.parseDouble(split[3]), Long.parseLong(split[4]));
        }).assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<OrderBean>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<OrderBean>() {
                            @Override
                            public long extractTimestamp(OrderBean element, long recordTimestamp) {
                                return element.getCreate_time();
                            }
                        }));


        // 每 5分钟，成交金额最高的前3种商品及其成交金额
        mapped.windowAll(TumblingEventTimeWindows.of(Time.minutes(5)))
                .process(new ProcessAllWindowFunction<OrderBean, String, TimeWindow>() {
                    @Override
                    public void process(ProcessAllWindowFunction<OrderBean, String, TimeWindow>.Context context, Iterable<OrderBean> elements, Collector<String> out) throws Exception {

                        HashMap<String, Double> tmpMap = new HashMap<>();

                        // 统计各商品的成交总金额
                        for (OrderBean orderBean : elements) {
                            String categoryId = orderBean.getCategoryId();
                            String productId = orderBean.getProductId();

                            double money = orderBean.getMoney();

                            String key = categoryId +":" +productId;

                            // 取出此前的累加值
                            Double oldMoney = tmpMap.getOrDefault(key, 0d);
                            tmpMap.put(key,oldMoney+money);
                        }

                        // 按金额排序，取前3
                        long start = context.window().getStart();
                        long end = context.window().getEnd();

                        // 先遍历统计map，将数据转成javabean，放入一个list
                        ArrayList<ResultBean> beanList = new ArrayList<>();
                        for (Map.Entry<String, Double> entry : tmpMap.entrySet()) {
                            String key = entry.getKey();
                            String[] split = key.split(":");
                            String cid = split[0];
                            String pid = split[1];

                            Double money = entry.getValue();

                            ResultBean resultBean = new ResultBean(start, end, cid, pid, money, 0);

                            beanList.add(resultBean);
                        }

                        // 对list中的javabean按照金额排序
                        Collections.sort(beanList, new Comparator<ResultBean>() {
                            @Override
                            public int compare(ResultBean o1, ResultBean o2) {
                                return Double.compare(o2.getMoney(), o1.getMoney());
                            }
                        });


                        // 对排好序的list取前3
                        for(int i = 0; i< Math.min(beanList.size(),3); i++){

                            ResultBean resultBean = beanList.get(i);
                            resultBean.setRank(i+1);

                            String json = JSON.toJSONString(resultBean);
                            out.collect(json);

                        }

                    }
                });
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class ResultBean{

    private long window_start;
    private long window_end;
    private String categoryId;
    private String productId;
    private double money;
    private int rank;

}
